package com.h3bpm.web.service.impl;

import OThinker.Common.Data.Database.Parameter;
import OThinker.Common.Data.DbType;
import OThinker.Common.Organization.Models.User;
import OThinker.H3.Controller.RestfulApi.cloudpivot.ResponseResult;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import OThinker.H3.Entity.WorkItem.WorkItemModels.WorkItem;
import com.h3bpm.web.qjcEnum.ContractStatusEnum;
import com.h3bpm.web.service.LegalLetterService;
import data.DataRow;
import data.DataRowCollection;
import data.DataTable;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import static OThinker.H3.Controller.ControllerBase.getEngine;


/**
 * 法务函Service的实现
 *
 * @author leo
 */
@Service
public class LegalLetterServiceImpl implements LegalLetterService {

    private static final Logger logger = LoggerFactory.getLogger(LegalLetterServiceImpl.class);

    @Override
    public boolean getLegalLetterNum(String objectId) {
        Parameter[] param = new Parameter[1];
        param[0] = new Parameter("objectId", DbType.String, objectId);
        String selectSql = "select legalLetterNumber  from i_applyforlegalletter where objectId=?";
        DataTable countDataTable = getEngine().getQuery().QueryTable(selectSql, param, false);
        try {
            DataRowCollection countRows = countDataTable.getRows();
            String legalNum = "legalLetterNumber";
            if (countRows != null && countRows.size() > 0 && !"".equals(countRows.get(0).getString(legalNum)) && countRows.get(0).getString(legalNum) != null) {
                DataRow dataRow = countRows.get(0);
                String dataRowString = dataRow.getString(legalNum);
                // 已生成法务函合同号
                if (null != dataRowString &&! "".equals(dataRowString)) {
                    logger.info("已生成法务函合同号： {} ,无需再次生成",dataRowString);
                    return false;
                }
            }

            Calendar cale = Calendar.getInstance();
            int year = cale.get(Calendar.YEAR);
            Parameter[] parameter = new Parameter[1];
            parameter[0] = new Parameter("legalLetterNumber", DbType.String, year);
            String templateData = "戚机审（律）函";
            String sql = "select COUNT(1) as count from i_applyforlegalletter where legalLetterNumber is not null and legalLetterNumber !=\"\" and yearStr=?";
            String letterNumber = null;
            String templateRow = "count";
            DataTable dataTable = getEngine().getQuery().QueryTable(sql, parameter, false);
            DataRowCollection rows = dataTable.getRows();
            if (rows != null && rows.size() > 0 && !"".equals(rows.get(0).getString(templateRow)) && rows.get(0).getString(templateRow) != null) {
                DataRow dataRow = rows.get(0);
                int count = dataRow.getInt("count");
                logger.info("获取到申请法务函总数,count {}", count);
                //如果为空，代表未有法务函编号生成，要生成为第一个法务函编号
                StringBuilder stringBuilder = new StringBuilder();
                StringBuilder appendStr = stringBuilder.append("(").append(year).append(")").append(templateData);
                if (count == 0) {
                    StringBuilder letterNum = appendStr.append("001");
                    letterNumber = letterNum.toString();
                    logger.info("第一个法务函编号,legalLetterNum = {}", letterNumber);
                } else {
                    // 不为要生成第一个，则现有总数+1为法务函新流水号
                    String formatStr;
                    String countStr = String.valueOf(count + 1);
                    // 法务函新流水号大于三位，则直接拼接
                    if (countStr.length() <= 3) {
                        formatStr = StringUtils.leftPad(countStr, 3, "0");
                    } else {
                        formatStr = countStr;
                    }
                    letterNumber = appendStr.append(formatStr).toString();
                    logger.info("非第一个法务函编号,legalLetterNum = {}", letterNumber);
                }
            }
            logger.info("法务函编号,legalLetterNum = {}", letterNumber);
            String updateSql = "UPDATE i_applyforlegalletter SET legalLetterNumber = ? WHERE ObjectID = ?";
            Parameter[] params = new Parameter[2];
            params[0] = new Parameter("legalLetterNumber", DbType.String, letterNumber);
            params[1] = new Parameter("ObjectID", DbType.String, objectId);
            int i = getEngine().getPortalQuery().ExcuteNoQuery(updateSql, params);
            if (i > 0) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            logger.error("获取第法务函编号发生错误, e = {}", e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
}
